import axios from "axios";
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { loginSuccess } from "../../app/user/userSlice";

const Index: React.FC = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const login = async () => {
    const resp = await axios.post("/api/login", { username, password });
    const { code, data, message } = resp.data;
    if (code === 200) {
      navigate("/my");
      dispatch(loginSuccess(data));
    } else {
      alert("账户密码错误");
    }
  };

  return (
    <div>
      <div>
        <input
          type="text"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
        />
      </div>
      <div>
        <input
          type="text"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
      </div>
      <button onClick={login}>登录</button>
    </div>
  );
};

export default Index;
